//
//  AssetListManager.swift
//  MyVideo
//
//  Created by han on 2021/4/22.
//

import UIKit
import AVFoundation

class AssetListManager: NSObject {
    static let shared = AssetListManager()
    private var assets = [Asset]()
    
    private override init() {
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(handleAssetPersistenceManagerDidRestoreState(_:)), name: .AssetPersistenceManagerDidRestoreState, object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self, name: .AssetPersistenceManagerDidRestoreState, object: nil)
    }
    
    
    func numberOfAssets() -> Int { assets.count }
    func asset(_ index: Int) -> Asset { assets[index] }
    
    // 加载asset: persistenceManager 和 本地 和 初始化三种途径
    @objc func handleAssetPersistenceManagerDidRestoreState(_ notification: Notification) {
        DispatchQueue.main.async {
            for stream in StreamListManager.shared.streams {
                if let asset = AssetPersistenceManager.shared.assetForStream(withName: stream.name) {
                    if !self.assets.contains(where: { $0.stream == asset.stream }) {
                        self.assets.append(asset)
                    }
                } else {
                    if let asset = AssetPersistenceManager.shared.localAssetForStream(with: stream.name) {
                        if !self.assets.contains(where: { $0.stream == asset.stream }) {
                            self.assets.append(asset)
                        }
                    } else {
                        let asset = Asset(stream: stream, urlAsset: AVURLAsset(url: URL(string: stream.playlistURL)!))
                        if !self.assets.contains(where: { $0.stream == asset.stream }) {
                            self.assets.append(asset)
                        }
                    }
                }
            }
            // asset list 加载完成
            NotificationCenter.default.post(name: .AssetListManagerDidLoad, object: self)
        }
    }
}


extension Notification.Name {
    static let AssetListManagerDidLoad = Notification.Name("AssetListManagerDidLoadNotification")
}
